import { defineStore } from 'pinia'
import type { ILogin } from './type'
import type { IAccount, IResponseData, IUserData, IUserMenu, IUserMenuResponse, IUserResponse } from '@/services/login/type'
import { accountLoginRequest, getUserInfoById, getUserMenuByRoleId } from '@/services/login'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { CACHE_USERINFO, CACHE_USERMENUS, LOGIN_TOKEN } from '@/global/constant'
import { mapMenuList2Permission, mapMenusToRoutes } from '@/utils/map-menus'
import useMainStore from '../main/main'

const useLoginStore = defineStore('login', {
  state: (): ILogin => ({
    name: '',
    id: '',
    token: '',
    userInfo: {},
    userMenus: [],
    permission: []
  }),
  actions: {
    async loginIAccountAction(IAccount: IAccount) {
      const res: IResponseData = await accountLoginRequest(IAccount)
      if (res.code === 0) {
        this.token = res.data.token
        this.name = res.data.name
        this.id = res.data.id

        // 1.本地存储
        localCache.setCache(LOGIN_TOKEN, this.token)
        // 2.获取登陆用户的详细信息
        const userInfoResult: IUserResponse = await getUserInfoById(this.id as number)
        this.userInfo = userInfoResult.data as IUserData
        // 3.根据角色id获取菜单
        const userMenu: IUserMenuResponse = await getUserMenuByRoleId(this.userInfo.id as number)
        this.userMenus = userMenu.data as IUserMenu[]
        localCache.setCache(CACHE_USERINFO, this.userInfo)
        localCache.setCache(CACHE_USERMENUS, this.userMenus)

        // 4. 请求需要的所有数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 5. 用户按钮映射
        const permission = mapMenuList2Permission(this.userMenus)
        this.permission = permission

        // 6. 用户菜单映射
        const { routes } = mapMenusToRoutes(this.userMenus)
        routes.forEach((route) => router.addRoute('main', route))
        // 7. 页面跳转
        const redirect = window.location.href.split('redirect=')[1]
        router.push(redirect ? redirect : '/main')
      } else {
        return Promise.reject(new Error('登陆失败'))
      }
    },

    // 防止用户刷新页面获取不到动态路由（loginIAccountAction这个action只有在用户点击登陆时才会操作）
    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache(CACHE_USERINFO)
      const userMenus = localCache.getCache(CACHE_USERMENUS)
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 全部数据容易丢失，重新请求数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()
      }

      const permission = mapMenuList2Permission(userMenus)
      this.permission = permission
      // 动态添加路由
      const { routes } = mapMenusToRoutes(userMenus)
      routes.forEach((route) => router.addRoute('main', route))
    }
  },
  getters: {}
})

export default useLoginStore
